package com.test.latitudex;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.test.latitudex.utilities.LocationBroadcastReceiver;
import com.test.latitudex.utilities.MyListAdapter;
import com.test.latitudex.utilities.RegistrationManager;

/**
 * A dummy fragment representing a section of the app, but that simply displays dummy text.
 */
public class FriendsFragment extends android.support.v4.app.Fragment {
	/**
	 * The fragment argument representing the section number for this fragment.
	 */
	public static final String ARG_SECTION_NUMBER = "section_number";
	private static final String LOG_TAG = "FriendsActivity";
	int minTime, minDist;

	static String interval = null, duration = null, id = null;
	static Button btn1;
	static Button btn2;
	static Button btn3;
	static EditText et1;
	static EditText et2;
	static EditText et3;
	static TextView tv1;
	static String userId;
	static LocationBroadcastReceiver brc;
	static Context ctx;
	static Activity act;
	static String lastUpdate = null;
	static boolean serviceStarted = false;
	static ListView list;
	static MyListAdapter adapter;
	static ProgressDialog progDialog;
	static int noDataFriends = 0; 
	static FriendsFragment frg;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		ctx = this.getActivity();
		act = this.getActivity();
		frg = this;
		list = (ListView) (getView().findViewById(R.id.friendsList));
		TextView name = (TextView) (getView().findViewById(R.id.myName)); // title
		TextView lastUpdated = (TextView) (getView().findViewById(R.id.myLastUpdated)); // duration
		ImageView thumb_image = (ImageView) (getView().findViewById(R.id.myList_image)); // thumb
																							// image
		Drawable d = getResources().getDrawable(R.drawable.thumb);
		thumb_image.setImageDrawable(d);
		name.setText(RegistrationManager.getEntity().getSelfData().get(MyListAdapter.KEY_NAME));

		
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm", Locale.getDefault());
		try {
			if(RegistrationManager.getEntity().getSelfData().get(MyListAdapter.KEY_DATE) != null){
				Date date = format.parse(RegistrationManager.getEntity().getSelfData().get(MyListAdapter.KEY_DATE));
				long diff = new Date().getTime() - date.getTime();
				long seconds = diff / 1000;
				long minutes = seconds / 60;
				long hours = minutes / 60;
				long days = hours / 24;
				String diffStr = "";
				if (days > 0) {
					diffStr = String.valueOf(days) + " days and "
							+ String.valueOf((diff - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60)) + " hours ago";
				} else if (hours > 0) {
					diffStr = String.valueOf(hours) + " hours and "
							+ String.valueOf((diff - (1000 * 60 * 60 * hours)) / (1000 * 60)) + " minutes ago";
				} else if (minutes > 0) {
					diffStr = String.valueOf(minutes) + " minutes and "
							+ String.valueOf((diff - (1000 * 60 * minutes)) / 1000) + " seconds ago";
				} else {
					diffStr = String.valueOf(seconds) + " seconds ago";
				}
				lastUpdated.setText(diffStr);
			}else{
				lastUpdated.setText("No data uploaded yet.");
			}
			

		} catch (ParseException e) {
			Log.e(LOG_TAG, e.getMessage());
		}

		adapter = new MyListAdapter(this.getActivity());
		list.setAdapter(adapter);

		list.setLongClickable(true);
		list.setOnItemLongClickListener(new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
				deleteFriend(position);
				return true;
			}
		});

		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				if(MyMapFragment.setMapPos(((TextView)arg1.findViewById(R.id.name)).getText().toString())){
					MainActivity.pager(2);
				}
				//fetchContacts();
					}
		});

	}

	public static void deleteFriendFromData(int position) {
		RegistrationManager.getEntity().getFriendData().remove(position);
		((Activity) ctx).runOnUiThread(new Runnable() {

			@Override
			public void run() {
				adapter = new MyListAdapter(act);
				list = (ListView) (act.findViewById(R.id.friendsList));
				list.setAdapter(adapter);
				MyMapFragment.setMap();
				list.invalidate();
			}

		});

	}
	
	
	public ArrayList<String> getNameEmailDetails(){
        ArrayList<String> names = new ArrayList<String>();
        ContentResolver cr = getActivity().getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {
                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                Cursor cur1 = cr.query( 
                        ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", 
                                new String[]{id}, null); 
                while (cur1.moveToNext()) { 
                    //to get the contact names
                    String name=cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    Log.e("Name :", name);
                    String email = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                    Log.e("Email", email);
                    if(email!=null){
                        names.add(name);
                    }
                } 
                cur1.close();
            }
        }
        return names;
    }
	
	@Override
	public void onActivityResult(int reqCode, int resultCode, Intent data) {
	  super.onActivityResult(reqCode, resultCode, data);

	  switch (reqCode) {
	    case (100) :
	      if (resultCode == Activity.RESULT_OK) {
	        Uri contactData = data.getData();
	        Cursor c =  getActivity().getContentResolver().query(contactData, null, null, null, null);
	        if (c.moveToFirst()) {
	          String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
	          // TODO Whatever you want to do with the selected contact name.
	        }
	      }
	      break;
	  }
	}
	
	public void fetchContacts() {

		String phoneNumber = null;
		String email = null;

		Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
		String _ID = ContactsContract.Contacts._ID;
		String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
		String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;

		Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
		String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
		String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;

		Uri EmailCONTENT_URI =  ContactsContract.CommonDataKinds.Email.CONTENT_URI;
		String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
		String DATA = ContactsContract.CommonDataKinds.Email.DATA;

		StringBuffer output = new StringBuffer();

		ContentResolver contentResolver = getActivity().getContentResolver();

		Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null);	

		// Loop for every contact in the phone
		if (cursor.getCount() > 0) {

			while (cursor.moveToNext()) {

				String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
				String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));

				int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER )));

				if (hasPhoneNumber > 0) {

					output.append("\n First Name:" + name);

					// Query and loop for every phone number of the contact
					Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);

					while (phoneCursor.moveToNext()) {
						phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
						output.append("\n Phone number:" + phoneNumber);

					}

					phoneCursor.close();

					// Query and loop for every email of the contact
					Cursor emailCursor = contentResolver.query(EmailCONTENT_URI,	null, EmailCONTACT_ID+ " = ?", new String[] { contact_id }, null);

					while (emailCursor.moveToNext()) {

						email = emailCursor.getString(emailCursor.getColumnIndex(DATA));

						output.append("\nEmail:" + email);

					}
					
					emailCursor.close();
				}

				output.append("\n");
			}

			Log.e("tag",output.toString());
		}
	}
	
	public static void refreshSelfData(){
		TextView name = (TextView) (frg.getView().findViewById(R.id.myName)); // title
		TextView lastUpdated = (TextView) (frg.getView().findViewById(R.id.myLastUpdated)); // duration
		ImageView thumb_image = (ImageView) (frg.getView().findViewById(R.id.myList_image)); // thumb
																							// image
		Drawable d = frg.getResources().getDrawable(R.drawable.thumb);
		thumb_image.setImageDrawable(d);
		name.setText(RegistrationManager.getEntity().getSelfData().get(MyListAdapter.KEY_NAME));
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm", Locale.getDefault());
		try {
			if(RegistrationManager.getEntity().getSelfData().get(MyListAdapter.KEY_DATE) != null){
				Date date = format.parse(RegistrationManager.getEntity().getSelfData().get(MyListAdapter.KEY_DATE));
				long diff = new Date().getTime() - date.getTime();
				long seconds = diff / 1000;
				long minutes = seconds / 60;
				long hours = minutes / 60;
				long days = hours / 24;
				String diffStr = "";
				if (days > 0) {
					diffStr = String.valueOf(days) + " days and "
							+ String.valueOf((diff - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60)) + " hours ago";
				} else if (hours > 0) {
					diffStr = String.valueOf(hours) + " hours and "
							+ String.valueOf((diff - (1000 * 60 * 60 * hours)) / (1000 * 60)) + " minutes ago";
				} else if (minutes > 0) {
					diffStr = String.valueOf(minutes) + " minutes and "
							+ String.valueOf((diff - (1000 * 60 * minutes)) / 1000) + " seconds ago";
				} else {
					diffStr = String.valueOf(seconds) + " seconds ago";
				}
				lastUpdated.setText(diffStr);
			}else{
				lastUpdated.setText("No data uploaded yet.");
			}
			RelativeLayout rl = (RelativeLayout) (act.findViewById(R.id.myProfile));
			rl.invalidate();

		} catch (ParseException e) {
			Log.e(LOG_TAG, e.getMessage());
		}
	}
	
	public static void refreshFriendData() {
		try {
			if(RegistrationManager.getEntity().downloadData()){
				((Activity) ctx).runOnUiThread(new Runnable() {

					@Override
					public void run() {
						adapter = new MyListAdapter(act);
						list = (ListView) (act.findViewById(R.id.friendsList));
						list.setAdapter(adapter);
						MyMapFragment.setMap();
						list.invalidate();
						refreshSelfData();
						
					}

				});
			}
		} catch (Exception e) {
			((Activity) ctx).runOnUiThread(new Runnable() {

				@Override
				public void run() {
					Toast.makeText(ctx, "Network unreachable. Please try later.", Toast.LENGTH_SHORT).show();
				}

			});
		}
		
		

	}
	

	public void deleteFriend(int position) {
		DialogFragment newFragment = new DeleteFriendDialogFragment();
		DeleteFriendDialogFragment.setPos(position);
		newFragment.show(getActivity().getSupportFragmentManager(), "DeleteFriend");
	}

	public static class DeleteFriendDialogFragment extends DialogFragment {
		private static int position;

		public static void setPos(int position) {
			DeleteFriendDialogFragment.position = position;
		}

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Use the Builder class for convenient dialog construction
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setMessage(R.string.deleteDialogText)
					.setPositiveButton(R.string.yesButton, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							act.runOnUiThread(new Runnable() {

								@Override
								public void run() {
									progDialog = ProgressDialog
											.show(act, "", "Contacting server... Please wait!", true);

								}

							});
							if (RegistrationManager.getEntity().deleteFriend(
									RegistrationManager.getEntity().getFriendData().get(position)
											.get(MyListAdapter.KEY_ID))) {

								FriendsFragment.deleteFriendFromData(position);
							}
							progDialog.dismiss();

						}
					}).setNegativeButton(R.string.noButton, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {

						}
					});
			// Create the AlertDialog object and return it
			return builder.create();
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.friends_activity_layout, container, false);
		return rootView;
	}

}